//
//  BRStationSearchVC.m
//  Kexu
//
//  Created by IOS on 2023/7/14.
//

#import "BRStationSearchVC.h"
#import "BRMapView.h"
#import "BRSearchView.h"
#import "BRStationSearchCell.h"

@interface BRStationSearchVC ()<BRMapViewDelegate,QMUITableViewDelegate,QMUITableViewDataSource>

@property (nonatomic,strong) UIView *contView;

@property (nonatomic,strong) BRMapView *mapView;

@property (nonatomic,strong) BRSearchView *searchView;
/// 位置APP
@property (nonatomic,strong) QMUIButton *locationBtn;

@property (nonatomic,strong) QMUIButton *confirmBtn;

@property (nonatomic,strong) NSMutableArray *dataList;

@property (nonatomic,strong) NSString *searchStr;

@end

@implementation BRStationSearchVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.dataList = [NSMutableArray array];
    self.searchStr = @"";
    [self setUI];
    [self br_blockAction];
    [self.mapView startUpdatingLocation];
    
    [self br_findCurrLocation];
}

#pragma mark - net --
- (void)searchLoction {
//    [BRHud showInView:self.view];
//    NSString *place = self.searchStr;
//
//    GMSAutocompleteSessionToken *token = [[GMSAutocompleteSessionToken alloc] init];
//
//    // Create a type filter.
//    GMSAutocompleteFilter *_filter = [[GMSAutocompleteFilter alloc] init];
////    _filter.types = @[ kGMSPlaceTypeBank ];
//    GMSPlacesClient *placesClient = [GMSPlacesClient sharedClient];
//    [placesClient findAutocompletePredictionsFromQuery:place filter:_filter sessionToken:token callback:^(NSArray<GMSAutocompletePrediction *> * _Nullable results, NSError * _Nullable error) {
//
//        [BRHud hiddenInView:self.view];
//        if (error != nil) {
//            NSString *errStr =  [error localizedDescription];
//            NSLog(@"An error occurred %@", errStr);
//
//            [BRHud show:errStr inView:self.view];
//            return;
//        }
//        [self.dataList removeAllObjects];
//        if (results != nil) {
//            for (GMSAutocompletePrediction *result in results) {
//
//                BRGMSPlaceModel *model = [[BRGMSPlaceModel alloc] init];
//                model.placeID = result.placeID;
//                model.place = result.attributedPrimaryText.string;
//                model.address = result.attributedFullText.string;
//                [self.dataList addObject:model];
//            }
//            if (self.dataList.count != 0) {
//                BRGMSPlaceModel *modelS = self.dataList.firstObject;
//                modelS.isSel = YES;
//
//                [self br_gmsFindPalceId:modelS.placeID];
//            }
//        }
//        [self.tableView reloadData];
//    }];
}

- (void)br_gmsFindPalceId:(NSString *)placeId {
    
//    [BRHud showInView:self.view];
//    GMSPlacesClient *placesClient = [GMSPlacesClient sharedClient];
//
//    [placesClient lookUpPlaceID:placeId callback:^(GMSPlace * _Nullable result, NSError * _Nullable error) {
//        [BRHud hiddenInView:self.view];
//        if (error != nil) {
//            NSString *errStr =  [error localizedDescription];
//            NSLog(@"An error occurred %@", errStr);
//
//            [BRHud show:errStr inView:self.view];
//            return;
//        }
//
//        CLLocationCoordinate2D curCoordinate2D = result.coordinate;
//        [self.mapView br_animateToCameraPosition:curCoordinate2D];
//    }];
    
//    [placesClient fetchPlaceFromPlaceID:placeId placeFields:GMSPlaceFieldAll sessionToken:nil callback:^(GMSPlace * _Nullable result, NSError * _Nullable error) {
//        [BRHud hiddenInView:self.view];
//        if (error != nil) {
//            NSString *errStr =  [error localizedDescription];
//            NSLog(@"An error occurred %@", errStr);
//
//            [BRHud show:errStr inView:self.view];
//            return;
//        }
//
//        CLLocationCoordinate2D curCoordinate2D = result.coordinate;
//        GMSCameraPosition *camera =  [GMSCameraPosition cameraWithLatitude:curCoordinate2D.latitude longitude:curCoordinate2D.longitude zoom:10];
//
//        [self.mapView.mapView animateToCameraPosition:camera];
//    }];
    
}

- (void)br_findCurrLocation {
    
//    GMSPlacesClient *placesClient = [GMSPlacesClient sharedClient];
//    [placesClient currentPlaceWithCallback:^(GMSPlaceLikelihoodList * _Nullable likelihoodList, NSError * _Nullable error) {
//
//        if (error != nil) {
//            NSString *errStr =  [error localizedDescription];
//            NSLog(@"An error occurred %@", errStr);
//
//            [BRHud show:errStr inView:self.view];
//            return;
//        }
//        if (likelihoodList != nil) {
//
//            [self.dataList removeAllObjects];
//            for (GMSPlaceLikelihood *place in likelihoodList.likelihoods) {
//
//                NSLog(@"place.name = [%@]",place.place.name);
//                BRGMSPlaceModel *model = [[BRGMSPlaceModel alloc] init];
//                model.placeID = place.place.placeID;
//                model.place = place.place.name;
//                model.address = place.place.formattedAddress;
//                model.curCoordinate2D = place.place.coordinate;
//                [self.dataList addObject:model];
//
//
//            }
//            if (self.dataList.count != 0) {
//                BRGMSPlaceModel *modelS = self.dataList.firstObject;
//                modelS.isSel = YES;
//                CLLocationCoordinate2D curCoordinate2D = modelS.curCoordinate2D;
//
//                [self.mapView br_animateToCameraPosition:curCoordinate2D];
//            }
//            [self.tableView reloadData];
//        }
//
//            
//    }];
}




#pragma mark - func --
- (void)toMyLocation:(QMUIButton *)btn {
    [self.mapView startUpdatingLocation];
}

- (void)toConfirm:(QMUIButton *)btn {
    
}

- (void)br_blockAction {
    WS(weakSelf);
    self.searchView.searchStrBlock = ^(NSString *place) {
        weakSelf.searchStr = place;
        [weakSelf searchLoction];
    };
    self.searchView.researchBlock = ^{
        weakSelf.searchStr = @"";
    };
}

#pragma mark - BRDelegate --
- (void)br_locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    
    ///
//    [self requestNearStation:self.mapView.myLocation];
}

- (void)br_mapView:(GMSMapView *)mapView willMove:(BOOL)gesture {
    
}

- (void)br_mapView:(GMSMapView *)mapView didChangeCameraPosition:(GMSCameraPosition *)position {
    
}

- (void)br_mapView:(GMSMapView *)mapView idleAtCameraPosition:(GMSCameraPosition *)position {
    
    NSLog(@"idleAtCameraPosition");
//    移动后刷新网点
//    position.;
}

- (BOOL)br_mapView:(GMSMapView *)mapView didTapMarker:(GMSMarker *)marker {
 
//    for (BRStationListModel *model in self.stationList) {
//        model.isTap = NO;
//        if (model.lat == marker.position.latitude && model.lng == marker.position.longitude) {
//            model.isTap = YES;
//            self.stationView.dto = model;
//            self.stationViewBG.hidden = NO;
//            WS(weakSelf);
//            self.stationView.locationClick = ^{
//                CLLocationCoordinate2D myL = weakSelf.mapView.myLocation;
//                CLLocationCoordinate2D toL = CLLocationCoordinate2DMake(model.lat, model.lng);
//                [BROpenURL openMap:myL toLocation:toL titleAddress:model.address];
//            };
//            [self.locationBtn mas_updateConstraints:^(MASConstraintMaker *make) {
//                make.bottom.equalTo(self.bottomeView.mas_top).offset(-122);
//            }];
//        }
//    }
//
//    [self.mapView setGMSMarkerShop:self.stationList];
    
    return YES;
}

- (void)br_mapView:(GMSMapView *)mapView didTapInfoWindowOfMarker:(GMSMarker *)marker {
    
}

- (void)br_mapView:(GMSMapView *)mapView didTapAtCoordinate:(CLLocationCoordinate2D)coordinate {
    
    
//    [self br_resetMapStation];
}

#pragma mark - table delegate --
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    

    return self.dataList.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    BRStationSearchCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BRStationSearchCell"];

    cell.dto = self.dataList[indexPath.row];
    
    return cell;
}

-  (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *placeId = @"";
    for (int i = 0; i < self.dataList.count; i++) {
        BRGMSPlaceModel *modelS = self.dataList[i];
        modelS.isSel = i == indexPath.row;
        if (i == indexPath.row) placeId = modelS.placeID;
    }
    [self br_gmsFindPalceId:placeId];
    [self.tableView reloadData];
}

#pragma mark - UI --
- (void)setUI {
    
    [self br_createTop:@""];
    
    [self.view addSubview:self.mapView];
    [self.mapView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(kSafeAreaTopHeight - 30);
        make.left.right.offset(0);
        make.height.mas_equalTo(280);
    }];
    [self.mapView resetGoogleBtnY:30];
    
   
    
    [self.view addSubview:self.contView];
    [self.contView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mapView.mas_bottom).offset(-30);
        make.left.right.offset(0);
        make.bottom.offset(10);
    }];
    
    //--------------我的位置-------------
    [self.view addSubview:self.locationBtn];
    [self.locationBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-14);
        make.width.height.mas_equalTo(52);
        make.bottom.equalTo(self.contView.mas_top).offset(-20);
    }];
    
    [self.contView addSubview:self.searchView];
    [self.searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(32);
        make.left.offset(14);
        make.right.offset(-14);
        make.top.offset(10);
    }];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = kColorBGFF;
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 12)];
    [self.contView addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.searchView.mas_bottom).offset(10);
        make.left.right.bottom.offset(0);
    }];
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([BRStationSearchCell class]) bundle:nil] forCellReuseIdentifier:@"BRStationSearchCell"];
    
    
    [BRToolsView br_addShadow:self.contView radius:8 shadowColor:UIColorMakeWithRGBA(0, 0, 0, 0.05)];
    
    [self.view bringSubviewToFront:self.navView];
    
}

#pragma mark - Lazy Load --
- (BRMapView *)mapView {
    
    if (_mapView == nil) {
        _mapView = [[BRMapView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 32, 220)];
        _mapView.delegate = self;
        _mapView.centImgView.imgBgView.hidden = YES;
        _mapView.mapView.myLocationEnabled = NO;
    }
    return _mapView;
}


- (UIView *)contView {
    
    if (_contView == nil) {
        _contView = [[UIView alloc] init];
        _contView.backgroundColor = UIColor.whiteColor;
        _contView.layer.cornerRadius = 10;
//        _contView.layer.masksToBounds = YES;
        
    }
    return _contView;
}

- (BRSearchView *)searchView {
    
    if (_searchView == nil) {
        
        _searchView = [[BRSearchView alloc] init];
        _searchView.placeholder = Localized(@"home_searchNearby");
    }
    return _searchView;
}

- (QMUIButton *)locationBtn {
    if (_locationBtn == nil) {
        _locationBtn = [[QMUIButton alloc] init];
        [_locationBtn setImage:UIImageMake(@"home_location") forState:UIControlStateNormal];
        _locationBtn.layer.cornerRadius = 26;
        _locationBtn.layer.masksToBounds = YES;
        [_locationBtn addTarget:self action:@selector(toMyLocation:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _locationBtn;
}

- (QMUIButton *)confirmBtn {
    
    if (_confirmBtn == nil) {
        _confirmBtn = [[QMUIButton alloc] init];;
        [_confirmBtn setTitle:Localized(@"home_confirm") forState:UIControlStateNormal];
        [_confirmBtn addTarget:self action:@selector(toConfirm:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _confirmBtn;
}

@end
